// import md5 from 'md5';
import _ from 'lodash';
import crypto from 'crypto';
import axios from 'axios'; 

function md5(text) {
    return crypto.createHash('md5').update(text).digest('hex');
}

function DSGet(q, b) {
    const s = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs";
    const t = Math.floor(Date.now() / 1000).toString();
    const r = Math.floor(Math.random() * (200000 - 100000 + 1) + 100000).toString();
    const br = b ? JSON.stringify(b) : "";
    const c = md5(`salt=${s}&t=${t}&r=${r}&b=${br}&q=${q}`);
    return `${t},${r},${c}`;
}

function gen_header(ds, cookie) {
    return {
        "DS": DSGet(ds),
        "x-rpc-app_version": "2.11.1",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
        "x-rpc-client_type": "5",
        "Referer": "https://webstatic.mihoyo.com/",
        "Cookie": cookie,
    };
}


class getres {
    constructor(url, server_id, role_id, ck) {
        this.url = url;
        this.server = server_id;
        this.uid = role_id;
        this.ck = ck;
    }

    async fetchData() {
         try {
            const req1 = await axios.get(this.url, {
                headers: gen_header(`role_id=${this.uid}&server=${this.server}`, this.ck)
            });
            return req1.data;
        } catch (error) {
            console.error(error);
            throw error; 
        }

    }

    async fetchmysuid(mysuid, ck) {
        try {
            const req2 = await axios.get(url, { headers: gen_header(`${mysuid}`, ck) });
            return req2.data;
        } catch (error) {
            console.error(error);
            throw error; 
        }
    }

    async fetchurl(){
        try {
          const req3 =await axios.get(url);
          return req3;
        } catch (error) {
          console.error(error);
       }
    }

    async checkcode(e, res, type, data = {}) {
        if (!res || !e) {
            this.e.reply('米游社接口请求失败，暂时无法查询');
            return false;
          }
          this.e = e;
          this.e.isSr = true;
          res.retcode = Number(res.retcode);
          switch (res.retcode) {
            case 0:
              break;
            case 10035:
            case 1034: {
              let handler = this.e.runtime?.handler || {};
      
              // 如果有注册的mys.req.err，调用
              if (handler.has('mys.req.err')) {
                logger.mark(
                  `[米游社查询失败][uid:${this.uid}]遇到验证码，尝试调用 Handler mys.req.err`
                );
                res =
                  (await handler.call('mys.req.err', this.e, {
                    mysApi: this,
                    type,
                    res,
                    data,
                    mysInfo: this,
                  })) || res;
              }
              if (!res || res?.retcode === 1034 || res?.retcode === 10035) {
                logger.mark(
                  `[米游社查询失败][uid:${this.uid}] 遇到验证码`
                );
                this.e.reply('米游社查询遇到验证码，请稍后再试');
              }
              break;
            }
            default:
              if (/(登录|login)/i.test(res.message)) {
                logger.mark(`[ck失效][uid:${this.uid}]`);
                this.e.reply(`UID:${this.uid}，米游社cookie已失效`);
              } else {
                this.e.reply(
                  `米游社接口报错，暂时无法查询：${res.message || 'error'}`
                );
              }
              break;
          }
          if (res.retcode !== 0) {
            logger.mark(
              `[米游社接口报错]${JSON.stringify(res)}，uid：${this.uid}`
            );
          }
          return res;
    }
}

export { getres };
